import React, { useRef } from 'react';

interface MarkdownEditorProps {
  title: string;
  content: string;
  onTitleChange: (title: string) => void;
  onContentChange: (content: string) => void;
  placeholder?: string;
}

const MarkdownEditor: React.FC<MarkdownEditorProps> = ({
  title,
  content,
  onTitleChange,
  onContentChange,
  placeholder = "Start writing..."
}) => {
  const textareaRef = useRef<HTMLTextAreaElement>(null);

  const handleKeyDown = (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
    const textarea = e.currentTarget;
    
    // Tab key handling for indentation
    if (e.key === 'Tab') {
      e.preventDefault();
      const start = textarea.selectionStart;
      const end = textarea.selectionEnd;
      const value = textarea.value;
      
      if (e.shiftKey) {
        // Remove indentation
        const lineStart = value.lastIndexOf('\n', start - 1) + 1;
        const line = value.substring(lineStart, value.indexOf('\n', start) === -1 ? value.length : value.indexOf('\n', start));
        
        if (line.startsWith('  ')) {
          const newValue = value.substring(0, lineStart) + line.substring(2) + value.substring(lineStart + line.length);
          onContentChange(newValue);
          setTimeout(() => {
            textarea.setSelectionRange(start - 2, end - 2);
          });
        }
      } else {
        // Add indentation
        const newValue = value.substring(0, start) + '  ' + value.substring(end);
        onContentChange(newValue);
        setTimeout(() => {
          textarea.setSelectionRange(start + 2, end + 2);
        });
      }
    }
    
    // Auto-complete brackets and quotes
    const pairs: { [key: string]: string } = {
      '(': ')',
      '[': ']',
      '{': '}',
      '"': '"',
      "'": "'",
      '`': '`'
    };
    
    if (pairs[e.key]) {
      e.preventDefault();
      const start = textarea.selectionStart;
      const end = textarea.selectionEnd;
      const value = textarea.value;
      const selectedText = value.substring(start, end);
      
      const newValue = value.substring(0, start) + e.key + selectedText + pairs[e.key] + value.substring(end);
      onContentChange(newValue);
      
      setTimeout(() => {
        textarea.setSelectionRange(start + 1, end + 1);
      });
    }
  };

  return (
    <div className="h-full flex flex-col">
      <div className="mb-4">
        <input
          type="text"
          value={title}
          onChange={(e) => onTitleChange(e.target.value)}
          placeholder="Article Title"
          className="w-full text-3xl font-bold bg-transparent border-none outline-none text-ios-gray-900 dark:text-white placeholder-ios-gray-400 dark:placeholder-ios-gray-500"
        />
      </div>
      
      <div className="flex-1 relative">
        <textarea
          ref={textareaRef}
          value={content}
          onChange={(e) => onContentChange(e.target.value)}
          onKeyDown={handleKeyDown}
          placeholder={placeholder}
          className="w-full h-full p-4 bg-white dark:bg-ios-gray-800 border border-ios-gray-200 dark:border-ios-gray-700 rounded-apple-lg resize-none outline-none focus:ring-2 focus:ring-ios-blue focus:border-transparent text-ios-gray-900 dark:text-white placeholder-ios-gray-400 dark:placeholder-ios-gray-500 font-mono text-sm leading-6"
          style={{ 
            minHeight: '400px',
            lineHeight: '1.6'
          }}
        />
        
        {/* Line numbers */}
        <div className="absolute left-2 top-4 text-xs text-ios-gray-400 dark:text-ios-gray-500 font-mono select-none pointer-events-none">
          {content.split('\n').map((_, index) => (
            <div key={index} style={{ lineHeight: '1.6' }}>
              {index + 1}
            </div>
          ))}
        </div>
      </div>
      
      {/* Status bar */}
      <div className="mt-4 flex justify-between items-center text-xs text-ios-gray-500 dark:text-ios-gray-400">
        <div className="flex space-x-4">
          <span>Lines: {content.split('\n').length}</span>
          <span>Words: {content.split(/\s+/).filter(word => word.length > 0).length}</span>
          <span>Characters: {content.length}</span>
        </div>
        <div>
          Markdown
        </div>
      </div>
    </div>
  );
};

export default MarkdownEditor;